//
//  RMMAddBookingOrderViewController.m
//  Romomo
//
//  Created by puman on 2017/2/14.
//  Copyright © 2017年 mazegong. All rights reserved.
//

#import "RMMAddBookingOrderViewController.h"
#import "RMMJiaDanBottomView.h"
#import "RMMMyHuLiTableViewCell.h"
#import "RMMJiaDanTuiJianTableViewCell.h"
#import "RMMGoodsDetialsViewController.h"
#import "RMMTaoCanDetailsViewController.h"
#import "RMMHuLiDetailsViewController.h"
#import "RMMGoodsConfirmViewController.h"
#import "RMMShopingModel.h"

@interface RMMAddBookingOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMAddBookingOrderViewController
{
    UITableView *_tableView;
    RMMJiaDanBottomView *_jiaDanBottomView;
    NSMutableArray *_taoCanArray;
    NSMutableArray *_tuiJianArray;
    NSMutableDictionary *_dataDic;
    NSArray *_keyArray;
    CGFloat _totalPrice;
}
- (void)dealloc{
    [RMMFileManager shareHandle].isAddBookingOrder = NO;
    NSLog(@"我被消费了啊 啊啊啊啊啊啊啊啊");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择加单项目";
    self.view.backgroundColor = kWhiteColor;
    [self addViews];
    [self getMyTaoCanData];
    // Do any additional setup after loading the view.
}
- (void)getData{
//    dispatch_group_t group = dispatch_group_create();
//    dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
//        // 并行执行的线程二
//        [self getMyTaoCanData];
//    });
//    dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
//        // 并行执行的线程三
//        [self getTuiJianData];
//    });
//    
//    dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
//        // 汇总结果
//        [_tableView reloadData];
//    });
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;
   // item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
    
}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
// 获取我的套餐
- (void)getMyTaoCanData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"CUST_ID"];
    NSString *url = GetCustBomUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            NSMutableArray *dataArr = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                NSArray *arr = dic[@"CARD_DETAILS"];
                for (NSDictionary *newDic in arr) {
                    RMMHuLiModel *model = [[RMMHuLiModel alloc] init];
                    [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:newDic]];
                    model.isSelect = @"0";
                    model.COUNT = @"1";
                    model.BOM_ID = dic[@"BOM_ID"];
                    NSString *time = [RMMFileManager retrunObjWith:model.END_DATE];
                    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
                    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
                    NSString *string = [inputFormatter stringFromDate:date];
                    if ([model.AVA_QTY integerValue] != 0) {
                        if ([time compare:string] == NSOrderedDescending) {
                            if ([model.IS_HOME isEqualToString:_isHome]) {
                                [dataArr addObject:model];
                            }
                        }
                    }
                }
            }
            if (dataArr.count) {
               [_dataDic setObject:dataArr forKey:@"我的套餐"];
            }
            [self getTuiJianData];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];

}
// 获取推荐项目
- (void)getTuiJianData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"prod_type"] = _isHome;;
    parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
    NSString *url =HomeGoodsUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            NSMutableArray *value = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                RMMHomeGoodsModel *model = [[RMMHomeGoodsModel alloc] init];
                [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:dic]];
                NSString *server_id = [NSString stringWithFormat:@"%@",model.SERVICE_ID];
                if (server_id.length > 0 && ![server_id isEqualToString:@"(null)"]) {
                    model.COUNT = @"1";
                    model.isSelcet = @"0";
                    model.MY_CARD_ID = @"0";
                    [value addObject:model];
                }
            }
            [_dataDic setObject:value forKey:@"推荐"];
            if ([_dataDic allKeys].count == 2) {
                _keyArray = @[@"我的套餐",@"推荐"];
            } else {
                _keyArray = @[@"推荐"];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
    } view:self.view];
}
- (void)addViews{
    [self addLeftItem];
    _taoCanArray = [NSMutableArray array];
    _tuiJianArray = [NSMutableArray array];
    _dataDic = [NSMutableDictionary dictionary];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = NO;
    [_tableView registerClass:[RMMJiaDanTuiJianTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMMyHuLiTableViewCell class] forCellReuseIdentifier:@"HuLiCell"];
    [self.view addSubview:_tableView];
    
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
    headLabel.backgroundColor = kBasicColor;
    headLabel.font = kFont(14);
    headLabel.text = [NSString stringWithFormat:@"您可增加%@分钟服务时间",_timeL];
    headLabel.textColor = kWhiteColor;
    headLabel.textAlignment = NSTextAlignmentCenter;
    _tableView.tableHeaderView = headLabel;
    
    _jiaDanBottomView = [[RMMJiaDanBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64 - 49, kScreenWideth, 49)];
    BUTTON_S(_jiaDanBottomView.goBuyBut, buyButClick);
    [self.view addSubview:_jiaDanBottomView];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _keyArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = _keyArray[section];
    NSMutableArray *value = _dataDic[key];
    return value.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = _keyArray[indexPath.section];
    if ([key isEqualToString:@"推荐"]) {
        return 80;
    } else {
        return 160;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
    view.backgroundColor = kCColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 40)];
    label.font = kFont(16);
    NSString *key = _keyArray[section];
    label.text = key;
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = _keyArray[indexPath.section];
    NSMutableArray *value = _dataDic[key];
    if ([key isEqualToString:@"推荐"]) {
        RMMJiaDanTuiJianTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = value[indexPath.row];
        cell.cellSelectBut.tag = 10000 *indexPath.section + indexPath.row;
        BUTTON_S(cell.cellSelectBut, selectButChlick:);
        return cell;
    } else {
        RMMMyHuLiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HuLiCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.selectBut.tag = 10000 *indexPath.section + indexPath.row;
        BUTTON_S(cell.selectBut, selectButChlick:);
        cell.model = value[indexPath.row];
        cell.subBut.tag = indexPath.row + 20000;
        cell.addBut.tag = indexPath.row + 30000;
        BUTTON_S(cell.subBut, subButClick:);
        BUTTON_S(cell.addBut, addButClick:);
        RMMHuLiModel *model = value[indexPath.row];
        if ([model.COUNT isEqualToString:@"1"]) {
            [cell.subBut setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = NO;
        } else {
            [cell.subBut setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = YES;
        }
        return cell;
    }
}
- (void)subButClick:(UIButton *)button{
    NSMutableArray *array = _dataDic[@"我的套餐"];
    NSInteger row = button.tag - 20000;
    RMMHuLiModel *model = array[row];
    NSInteger cout = [model.COUNT integerValue];
    if (cout == 1) {
        [button setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
        button.userInteractionEnabled = NO;
    } else {
        cout -= 1;
        model.COUNT = [NSString stringWithFormat:@"%ld",cout];
    }
    [_tableView reloadData];
    _jiaDanBottomView.youHuiLabel.text = [NSString stringWithFormat:@"服务时间:%ld分钟",[self getTotalTimeWith:_dataDic]];
}
- (void)addButClick:(UIButton *)button{
    NSMutableArray *array = _dataDic[@"我的套餐"];
    NSInteger row = button.tag - 30000;
    RMMHuLiModel *model = array[row];
    NSInteger cout = [model.COUNT integerValue];
    NSInteger ava_qty = [model.AVA_QTY integerValue];
    if (cout == ava_qty) {
        [RMMFileManager MBProgressWith:@"可用次数不足!" onView:self.view];
        return;
    }
    cout += 1;
    model.COUNT = [NSString stringWithFormat:@"%ld",cout];
    [_tableView reloadData];
    NSInteger totalTime = [self getTotalTimeWith:_dataDic];
    NSInteger canUseTime = [_timeL integerValue];
    if (totalTime > canUseTime) {
        model.COUNT = [NSString stringWithFormat:@"%ld",cout - 1];
        [RMMFileManager MBProgressWith:@"总时间超过可用时间!" onView:self.view];
        return;
    }
    _jiaDanBottomView.youHuiLabel.text = [NSString stringWithFormat:@"服务时间:%ld分钟",[self getTotalTimeWith:_dataDic]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = _keyArray[indexPath.section];
    NSMutableArray *value = _dataDic[key];
    if ([key isEqualToString:@"推荐"]) {
        RMMHomeGoodsModel *model = value[indexPath.row];
        NSString *bom_id = [RMMFileManager retrunObjWith:model.SERVICE_ID];
        if (bom_id.length > 0 && ![bom_id isEqualToString:@"(null)"]) {
            RMMGoodsDetialsViewController *VC = [[RMMGoodsDetialsViewController alloc] init];
            VC.service_id = model.SERVICE_ID;
            [self.navigationController pushViewController:VC animated:YES];
        } else {
            RMMTaoCanDetailsViewController *VC = [[RMMTaoCanDetailsViewController alloc] init];
            VC.bom_id = model.BOM_ID;
            [self.navigationController pushViewController:VC animated:YES];
        }
    } else {
        RMMHuLiDetailsViewController *VC = [[RMMHuLiDetailsViewController alloc] init];
        VC.model = value[indexPath.row];
        [self.navigationController pushViewController:VC animated:YES];
    }
}
- (void)selectButChlick:(UIButton *)button{
    NSInteger section = button.tag / 10000;
    NSString *key = _keyArray[section];
    NSMutableArray *array = _dataDic[key];
    NSInteger row = button.tag % 10000;
    NSInteger time = [self getTotalTimeWith:_dataDic];
    if ([key isEqualToString:@"我的套餐"]) {
        RMMHuLiModel *model = array[row];
        if ([model.isSelect isEqualToString:@"0"]) {
            model.isSelect = @"1";
            NSInteger totalTime = time + [model.TIME_LEN integerValue];
            NSInteger canUseTime = [_timeL integerValue];
            if (canUseTime < totalTime) {
                [RMMFileManager MBProgressWith:@"总时间超过可用时间!" onView:self.view];
                model.isSelect = @"0";
                return;
            }
        } else {
            model.isSelect = @"0";
        }
    } else {
        RMMHomeGoodsModel *model = array[row];
        if ([model.isSelcet isEqualToString:@"0"]) {
            model.isSelcet = @"1";
            NSInteger totalTime = time + [model.TIME_LEN integerValue];
            NSInteger canUseTime = [_timeL integerValue];
            if (canUseTime < totalTime) {
                [RMMFileManager MBProgressWith:@"总时间超过可用时间!" onView:self.view];
                model.isSelcet = @"0";
                return;
            }
        } else {
            model.isSelcet = @"0";
        }
    }
    [self getToatalPriceWithArray:_dataDic];
    _jiaDanBottomView.totalPriceLabel.text = [NSString stringWithFormat:@"总计:¥%.2f",_totalPrice];
    _jiaDanBottomView.youHuiLabel.text = [NSString stringWithFormat:@"服务时间:%ld分钟",[self getTotalTimeWith:_dataDic]];
    [_tableView reloadData];
}
// 得到全价钱的方法
- (CGFloat)getToatalPriceWithArray:(NSMutableDictionary *)dic{
    CGFloat totalPrcie = 0.00;
    BOOL isSelect = NO;
    for (NSString *key in dic) {
        NSArray *array = dic[key];
        if ([key isEqualToString:@"推荐"]) {
            for (RMMHomeGoodsModel *model in array) {
                if ([model.isSelcet isEqualToString:@"1"]) {
                    CGFloat prcie = [model.PRICE floatValue];
                    NSInteger count = [model.COUNT integerValue];
                    totalPrcie += prcie * count;
                }
            }
        }
    }
    for (NSString *key in dic) {
        NSArray *array = dic[key];
        if ([key isEqualToString:@"推荐"]) {
            for (RMMHomeGoodsModel *model in array) {
                if ([model.isSelcet isEqualToString:@"1"]) {
                    isSelect = YES;
                }
            }
        } else {
            for (RMMHuLiModel *model in array) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    isSelect = YES;
                }
            }
        }
    }
    if (isSelect) {
        [self goBuyButSelcet];
    } else {
        [self cancelButSelcet];
    }
    _totalPrice = totalPrcie;
    return totalPrcie;
}
// 得到时间的方法
- (NSInteger)getTotalTimeWith:(NSMutableDictionary *)dic{
    NSInteger totalTime = 0;
    for (NSString *key in dic) {
        NSArray *array = dic[key];
        if ([key isEqualToString:@"推荐"]) {
            for (RMMHomeGoodsModel *model in array) {
                if ([model.isSelcet isEqualToString:@"1"]) {
                    NSInteger count = [model.TIME_LEN integerValue];
                    totalTime += count;
                }
            }
            
        } else {
            for (RMMHuLiModel *model in array) {
                if ([model.isSelect isEqualToString:@"1"]) {
                    NSInteger count = [model.TIME_LEN integerValue];
                    NSInteger qty = [model.COUNT integerValue];
                    totalTime += count * qty;
                }
            }
        }
    }
    return totalTime;
}
// 去结算
- (void)buyButClick{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"order_id"] = _model.ORDER_ID;
    NSString *url = GetAddOrderDetailUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSDictionary *dic = [RMMFileManager setValueForDic:dataDic[@"data"]];
            RMMGoodsConfirmViewController *VC = [[RMMGoodsConfirmViewController alloc] init];
            VC.goodsArray = [NSMutableArray array];
            for (NSString *key in _dataDic) {
                NSMutableArray *value = _dataDic[key];
                if ([key isEqualToString:@"推荐"]) {
                    for (RMMHomeGoodsModel *model in value) {
                        if ([model.isSelcet isEqualToString:@"1"]) {
                            RMMShopingModel *shopModel = [[RMMShopingModel alloc] init];
                            shopModel.IMAGEURL = model.IMAGEURL;
                            shopModel.SERVICE_ID = [NSString stringWithFormat:@"%@",model.SERVICE_ID];
                            shopModel.PRICE = [NSString stringWithFormat:@"%@",model.PRICE];
                            shopModel.COUNT = @1;;
                            shopModel.SERVICE_NAME = model.NAME;
                            shopModel.TIME_LEN = model.TIME_LEN;
                            shopModel.isSelect = @"1";
                            shopModel.MY_CARD_ID = model.MY_CARD_ID;
                            [VC.goodsArray addObject:shopModel];
                        }
                    }
                } else {
                    for (RMMHuLiModel *model in value) {
                        if ([model.isSelect isEqualToString:@"1"]) {
                            RMMShopingModel *taoModel = [[RMMShopingModel alloc] init];
                            taoModel.IMAGEURL = model.SER_URL;
                            taoModel.SERVICE_ID = [NSString stringWithFormat:@"%@",model.SERVER_ID];
                            taoModel.PRICE = [NSString stringWithFormat:@"%@",model.PRICE];
                            taoModel.COUNT = [NSNumber numberWithInteger:[model.COUNT integerValue]];
                            taoModel.SERVICE_NAME = model.NAME;
                            taoModel.MY_CARD_ID = [NSString stringWithFormat:@"%@",model.MY_CARD_ID];
                            taoModel.isSelect = @"1";
                            taoModel.TIME_LEN = model.TIME_LEN;
                            taoModel.BOM_ID = model.BOM_ID;
                            [VC.goodsArray addObject:taoModel];
                        }
                    }
                }
                NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSString *nowTime = [dateFormatter stringFromDate:date];
                [[RMMFileManager shareHandle].bookingDic setValue:dic[@"BOOK_END_TIME"] forKey:@"时间"];
                if([nowTime compare:dic[@"BOOK_END_TIME"]] == NSOrderedDescending) {
                    [[RMMFileManager shareHandle].bookingDic setValue:nowTime forKey:@"时间"];
                }
                NSMutableDictionary *adressDic = [NSMutableDictionary dictionary];
                adressDic[@"MOBILE"] = dic[@"CUST_MOBILE"];
                adressDic[@"PROVINCE_NAME"] = dic[@"PROVINCE_NAME"];
                adressDic[@"CITY_NAME"] = dic[@"CITY_NAME"];
                adressDic[@"REGION_NAME"] = dic[@"REGION_NAME"];
                adressDic[@"DE_ADDRESS"] = dic[@"DE_ADDRESS"];
                adressDic[@"ADD_NAME"] = dic[@"ADD_NAME"];
                if (_model.IS_HOME) {
                    adressDic[@"ID"] = dic[@"ADDRESS_ID"];
                } else {
                    adressDic[@"ID"] = dic[@"STORE_ID"];
                }
                [[RMMFileManager shareHandle].bookingDic setValue:adressDic forKey:@"地址"];
                NSDictionary *emp_dic = @{@"EMP_NAME":dic[@"EMP_NAME"],@"EMP_ID":dic[@"EMP_ID"]};
                [[RMMFileManager shareHandle].bookingDic setValue:emp_dic forKey:@"技师"];
                [RMMFileManager shareHandle].region_id = dic[@"REGION_ID"];
            }
            VC.isHome = _model.IS_HOME;
            [RMMFileManager shareHandle].isAddBookingOrder = YES;
            [self.navigationController pushViewController:VC animated:YES];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
    } view:self.view];

}
- (void)goBuyButSelcet{
    [_jiaDanBottomView.goBuyBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    _jiaDanBottomView.goBuyBut.backgroundColor = COLORFROMCODE(0x53C7C6, 1);
    _jiaDanBottomView.goBuyBut.userInteractionEnabled = YES;
    _jiaDanBottomView.goBuyBut.layer.borderColor = kBasicColor.CGColor;
}
- (void)cancelButSelcet{
    [_jiaDanBottomView.goBuyBut setTitleColor:COLORFROMCODE(0xD7D7D7, 1) forState:(UIControlStateNormal)];
    _jiaDanBottomView.goBuyBut.backgroundColor = kWhiteColor;
    _jiaDanBottomView.goBuyBut.userInteractionEnabled = NO;
    _jiaDanBottomView.goBuyBut.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;

 
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
